﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RMS.DB
{
    class ShopInfoManager : DBController
    {
        /// <summary>
        /// Get an instance of Shop Info
        /// </summary>
        /// <returns></returns>
        public ShopInfo GetOne()
        {            
            try
            {
                var query = from shops in DataEntities.ShopInfo                                              
                                             select shops;

                return query.FirstOrDefault();
            }
            catch (Exception ex)
            {
                throw new Exception(Constants.Msg.ConnectError);
            }            
        }

        /// <summary>
        /// Save instance
        /// </summary>
        /// <param name="shopInfo"></param>
        /// <returns></returns>
        private int Save(ShopInfo shopInfo)
        {
            try
            {
                DataEntities.AddToShopInfo(shopInfo);
                return DataEntities.SaveChanges();
            }
            catch (Exception ex)
            {
                throw new Exception(Constants.Msg.ConnectError);
            }   
        }

        /// <summary>
        /// Update Shop info instance = Delete all + Save new one
        /// </summary>
        /// <param name="shopInfo"></param>
        /// <returns></returns>
        public int Update(ShopInfo shopInfo)
        {
            //Delete all old items
            int deleteResult = DeleteAll();

            if (deleteResult != 0)
            {
                return Save(shopInfo);
            }

            return 0;
        }
        
        /// <summary>
        /// Delete all records
        /// </summary>
        /// <returns></returns>
        public int DeleteAll()
        {
            try
            {
                var list = from shops in DataEntities.ShopInfo
                           select shops;

                if (list != null && list.Count() > 0)
                    foreach (var item in list)
                    {
                        DataEntities.DeleteObject(item);
                    }

                return DataEntities.SaveChanges();
            }
            catch (Exception ex)
            {
                throw new Exception(Constants.Msg.ConnectError);
            }   
        }
    }
}
